﻿using Business.Core;
using Business.Core.Annotations;
using Business.Core.Result;
using Business.Data;
using Common;
using DataModel;
using LinqToDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using ProjectManager.User.Model;
using ProjectManager.User;
using FangPage.Common;
using FangPage.Data;

namespace ProjectManagerSys
{
    /// <summary>
    /// 项目管理
    /// </summary>
    public class ProjectMerber : Common.BusinessBase
    {

        #region //项目
        [Doc("获取项目列表", Group = "项目管理")]
        public virtual async Task<dynamic> ProjectList(int page,int limit,string projectname,string leadername,
            string membername,DateTime? startTime,DateTime? endTime)
        {
            AuthInfo authinfo = Logins.Authorize();
            
            using (var con = Data.DB.GetConnection())
            {
                var list = con.MANAGER_PROJECT.AsQueryable();
                
                if (authinfo.isadmin != 1)
                {
                    var new_user = "," + authinfo.userid + ",";
                    if (string.IsNullOrEmpty(authinfo.departs)) //个人
                    {
                        list = list.Where(c => c.CREATENAME == authinfo.userid || c.UPDATENAME == authinfo.userid || c.PROJECTLEADER.Contains(new_user) || c.PROJIECTMEMBER.Contains(new_user));
                    }
                    else //部门
                    {
                        var arr_depart = authinfo.departid.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        list = list.Where(c => arr_depart.Contains(c.DEPARTCODE) || arr_depart.Contains(c.UPDATECODE) || c.PROJECTLEADER.Contains(new_user) || c.PROJIECTMEMBER.Contains(new_user));
                    }
                }
                list = list.Where(p=>p.ACTIVE==1);
                if (string.IsNullOrWhiteSpace(projectname) == false) //项目名称
                    list = list.Where(p => p.PROJECTNAME.Contains(projectname));
                if (string.IsNullOrWhiteSpace(leadername) == false)
                    list = list.Where(p => p.LEADERNAME.Contains(leadername));
                if (string.IsNullOrWhiteSpace(membername) == false)
                    list = list.Where(p=>p.MEMBERNAME.Contains(membername));
                list = startTime.HasValue && endTime.HasValue ? list = list.Where(p => p.STARTTIME >=startTime && p.ENDTIME <= endTime) : list;
                list = list.OrderByDescending(p=>p.STARTTIME);

                var pageData = list.GetPaging(page, limit);
                
                var result = new { code= 0 ,msg= "",count = pageData.Count , data = pageData.Data };

                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                return JsonConvert.SerializeObject(result, Formatting.Indented, timeFormat);
            }
        }

        [Doc("获取项目所有数据", Group = "项目管理")]
        public virtual async Task<dynamic> ProjectAllList()
        {
            using (var con = Data.DB.GetConnection())
            {
                return JsonConvert.SerializeObject(con.MANAGER_PROJECT.Where(c=>c.ACTIVE==1).ToList());
            }
        }

        [Doc("新增或者修改项目", Group = "项目管理")]
        public virtual async Task<IResult> AddOrUpdateProject(Arg<MANAGER_PROJECT> arg)
        {
            var flag = 0;
            try
            {
                AuthInfo authinfo = Logins.Authorize();
                MANAGER_PROJECT oProject = JsonConvert.DeserializeObject<MANAGER_PROJECT>(arg.In);
                oProject.UPDATETIME = DateTime.Now;
                oProject.ACTIVE = 1;
                oProject.UPDATENAME = authinfo.userid;
                oProject.UPDATECODE = authinfo.departid;
                //计算项目的开始时间到结束时间的工作日
                int w_days = 0;
                int h_days = 0;
                int b_days = 0;
                if (!string.IsNullOrEmpty(oProject.STARTTIME.ToString()) && !string.IsNullOrEmpty(oProject.ENDTIME.ToString()))
                {
                    w_days = DateOperation.GetWorkDays(Convert.ToDateTime(oProject.STARTTIME), Convert.ToDateTime(oProject.ENDTIME)); //周一到周五
                    h_days = new TimeValidate().GetDays(Convert.ToDateTime(oProject.STARTTIME), Convert.ToDateTime(oProject.ENDTIME), 1);//节假日
                    b_days = new TimeValidate().GetDays(Convert.ToDateTime(oProject.STARTTIME), Convert.ToDateTime(oProject.ENDTIME), 2);//补班
                }
                    
                oProject.DAYS = w_days - h_days + b_days;
                using (var con = Data.DB.GetConnection())
                {
                    if (string.IsNullOrEmpty(oProject.ID)) //新增
                    {
                        oProject.ID = Guid.NewGuid().ToString();
                        oProject.CREATETIME = DateTime.Now;
                        oProject.CREATENAME = authinfo.userid;
                        oProject.REALNAME = authinfo.realname;
                        oProject.DEPARTCODE = authinfo.departid;
                        
                        flag = await con.InsertAsync(oProject);
                    }
                    else //修改
                    {
                        var oModel = con.MANAGER_PROJECT.Where(x => x.ID == oProject.ID).FirstOrDefault();
                        oProject.CREATETIME = oModel.CREATETIME;
                        oProject.DEPARTCODE = oModel.DEPARTCODE;
                        oProject.CREATENAME = oModel.CREATENAME;
                        oProject.REALNAME = oModel.REALNAME;
                        oProject.STATUS = oModel.STATUS;
                        flag = await con.UpdateAsync(oProject);
                    }
                    FPLog.Info("loginuser","【projct】" + FPUtils.GetDateTime() + JsonConvert.SerializeObject(authinfo));
                    if (flag > 0 && !string.IsNullOrEmpty(oProject.ATTACHCODE))
                    {
                        string sql = string.Format("update BJSYS_ARRACH set UPDATETIME=sysdate,RESOURCEID='{0}',TABLENAME='MANAGER_PROJECT',EFFECT=1 where ATTACHCODE='{1}'", oProject.ID,oProject.ATTACHCODE);
                        con.ExecuteNonQuery(sql);
                    }
                }
                    
            }
            catch (Exception ex)
            {
                
            }
            //入库的用户
            return flag > 0 ? ResultCreate(flag) : ResultCreate(-111);
        }

        [Doc("修改项目", Group = "项目管理")]
        public virtual async Task<IResult> UpdateProject(Arg<MANAGER_PROJECT> arg)
        {
            try
            {
                MANAGER_PROJECT oProject = JsonConvert.DeserializeObject<MANAGER_PROJECT>(arg.In);
                using (var con = Data.DB.GetConnection())
                {
                    var flag = await con.UpdateAsync(oProject);
                    return flag > 0 ? ResultCreate(flag) : ResultCreate(-111);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [Doc("获取项目详情", Group = "项目管理")]
        public virtual async Task<IResult> GetProjectInfo(string id)
        {
            using (var con = Data.DB.GetConnection())
            {
                var data = con.MANAGER_PROJECT.Where(x => x.ID == id).FirstOrDefault();
                if (null == data)
                {
                    return ResultCreate(-111);
                }
                return ResultCreate(data);
            }
        }

        [Doc("逻辑删除项目", Group = "项目管理")]
        public virtual async Task<dynamic> DeleteProject(string delIds)
        {
            using (var con = Data.DB.GetConnection())
            {
                var flag = 0;
                if (!String.IsNullOrEmpty(delIds))
                {
                    var idArray = delIds.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (idArray.Length > 0)
                    {
                        foreach (var item in idArray)
                        {
                            var oModel = con.MANAGER_PROJECT.Where(c => c.ID == item).FirstOrDefault();
                            if (oModel != null)
                            {
                                oModel.ACTIVE = 0;
                                flag += await con.UpdateAsync(oModel);
                            }
                        }
                    }                   
                }

                return (flag);
            }
        }

        [Doc("根据项目id获取项目标题", Group = "项目管理")]
        public virtual async Task<dynamic> GetProjectTitle(string id)
        {
            using (var con = Data.DB.GetConnection())
            {
                var data = con.MANAGER_PROJECT.Where(x => x.ID == id).FirstOrDefault();
                if (null == data)
                {
                    return "";
                }
                return JsonConvert.SerializeObject(data.PROJECTNAME);
            }
        }

        [Doc("修改项目状态", Group = "项目管理")]
        public virtual async Task<dynamic> SetStatusById(string ids,int status)
        {
            int flag = 0;
            using (var con = Data.DB.GetConnection())
            {
                var idArray = ids.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                var data = con.MANAGER_PROJECT.Where(x =>idArray.Contains(x.ID)).ToList();
                if (data.Count > 0)
                {
                    AuthInfo authinfo = Logins.Authorize();
                    foreach (var item in data)
                    {
                        item.STATUS = status;
                        item.UPDATENAME = authinfo.userid;
                        item.UPDATETIME = DateTime.Now;
                        flag += await con.UpdateAsync(item);
                    }
                }
                return JsonConvert.SerializeObject(flag);
            }
        }

        
        #endregion

        #region //项目字典管理
        [Doc("项目字典列表", Group = "项目管理")]
        public virtual async Task<dynamic> ProjectDicList(int page, int limit, string title)
        {
            AuthInfo authinfo = Logins.Authorize();
            int count = 0;
            var list2 = new List<MANAGER_TASK_DIC>();
            using (var con = Data.DB.GetConnection())
            {
                var list = con.MANAGER_TASK_DIC.AsQueryable();

                list = list.Where(p => p.ACTIVE == 1 && p.TYPEDIC== "project");
                if (!string.IsNullOrWhiteSpace(title)) //项目名称
                    list = list.Where(p => p.CODENAME.Contains(title));

                list = list.OrderBy(p => new { p.TYPE, p.SORTINDEX });

                var pageData = list.GetPaging(page, limit);
                if (pageData.Count > 0)
                {
                    count = pageData.Count;
                    list2 = pageData.Data.ToList();
                }

                var result = new { code = 0, msg = "", count =count , data = list2 };

                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                return JsonConvert.SerializeObject(result, Formatting.Indented, timeFormat);
            }
        }

        [Doc("项目字典列表", Group = "项目管理")]
        public virtual async Task<dynamic> ProjectDicListAll()
        {
            using (var con = Data.DB.GetConnection())
            {
                var list = con.MANAGER_TASK_DIC.AsQueryable();

                list = list.Where(p => p.ACTIVE == 1 && p.TYPEDIC == "project");
                return JsonConvert.SerializeObject(list);
            }
        }

        [Doc("新增或者修改字典", Group = "项目管理")]
        public virtual async Task<dynamic> AddOrUpdateProjectDic(string arg)
        {
            int flag = 0;
            AuthInfo authinfo = Logins.Authorize();
            var oModel = JsonConvert.DeserializeObject<MANAGER_TASK_DIC>(arg);
            using (var con = Data.DB.GetConnection())
            {
                oModel.CREATETIME = DateTime.Now;
                oModel.USERID = authinfo.userid;
                oModel.TYPEDIC = "project";
                oModel.ACTIVE = 1;
                
                if (string.IsNullOrEmpty(oModel.ID)) //新增
                {
                    oModel.CODE = GetProjectDicMaxCode(oModel.TYPE).ToString();
                    oModel.ID = Guid.NewGuid().ToString();
                    flag = await con.InsertAsync(oModel);
                }
                else
                {
                    flag = await con.UpdateAsync(oModel);
                }
                return JsonConvert.SerializeObject(flag);
            }
        }

        [Doc("逻辑删除项目字典", Group = "项目管理")]
        public virtual async Task<dynamic> DeleteProjectDic(string delIds)
        {
            using (var con = Data.DB.GetConnection())
            {
                var flag = 0;
                if (!String.IsNullOrEmpty(delIds))
                {
                    var idArray = delIds.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (idArray.Length > 0)
                    {
                        foreach (var item in idArray)
                        {
                            var oModel = con.MANAGER_TASK_DIC.Where(c => c.ID == item).FirstOrDefault();
                            if (oModel != null)
                            {
                                oModel.ACTIVE = 0;
                                flag += await con.UpdateAsync(oModel);
                            }
                        }
                    }
                }

                return (flag);
            }
        }

        public int GetProjectDicMaxCode(decimal? type)
        {
            int flag = 0;
            using (var con = Data.DB.GetConnection())
            {
                var oModel = con.MANAGER_TASK_DIC.Where(c=>c.TYPE == type).OrderByDescending(c=>c.CODE).FirstOrDefault();
                if (oModel != null)
                    flag =Convert.ToInt32(oModel.CODE) + 1;
            }
            return flag;
        }
        #endregion
    }
}
